/*
 * Created on Mar 11, 2007
 * 
 * $Id: PolygonListRenderer.java Feb 8, 2004 izpack-frontend
 * Copyright (C) 2005 Andy Gombos
 * 
 * File : PolygonListRenderer.java 
 * Description : TODO Add description
 * Author's email : gumbo@users.berlios.de
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ui;

import geom.Line;
import geom.PolygonList;
import geom.Solid;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Area;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class PolygonListRenderer extends JPanel implements ActionListener, ChangeListener
{
	public PolygonListRenderer(Solid s)
	{		
		scaler = new SliceScaler(s);
		
		canvas = new ImageIcon();
		JScrollPane viewport = new JScrollPane();
		viewport.setViewportView(display = new ScrollablePicture(canvas, 1));

		JPanel zoomView = new JPanel();
		JSlider zoomer = new JSlider(JSlider.HORIZONTAL, 1, 2000, 100);
		zoomer.addChangeListener(this);
		zoomAmountLbl = new JLabel("100 %");

		zoomView.add(zoomer);
		zoomView.add(zoomAmountLbl);

		JPanel layerView = new JPanel();
		jOriginal = new JCheckBox("Original Shape");
		jOriginal.addActionListener(this);
		jBisectors = new JCheckBox("Bisectors");
		jBisectors.addActionListener(this);
		jInset = new JCheckBox("Inset");
		jInset.addActionListener(this);
		jVertex = new JCheckBox("View vertex order");
		jVertex.addActionListener(this);
		jMultColors = new JCheckBox("Separate colors per polygon");
		jMultColors.addActionListener(this);

		layerView.add(jOriginal);
		layerView.add(jBisectors);
		layerView.add(jInset);
		layerView.add(jVertex);
		layerView.add(jMultColors);

		setLayout(new BorderLayout());
		add(viewport, BorderLayout.CENTER);
		add(zoomView, BorderLayout.NORTH);
		add(layerView, BorderLayout.SOUTH);
		
		jOriginal.setSelected(true);
		jInset.setSelected(true);		
	}

	public void setPolygonList(PolygonList pList)
	{
		polys = pList;

		update();
	}

	public void actionPerformed(ActionEvent e)
	{
		viewOriginal = jOriginal.isSelected();
		viewBisectors = jBisectors.isSelected();
		viewInset = jInset.isSelected();
		viewVertex = jVertex.isSelected();
		viewMultColors = jMultColors.isSelected();

		update();
	}

	public void stateChanged(ChangeEvent e)
	{
		zoomAmount = ((JSlider) e.getSource()).getValue();
		zoomAmountLbl.setText(zoomAmount + "%");

		update();
	}

	private void update()
	{
		scaler.setZoomFactor(zoomAmount / 33.333333);

		Shape zOriginal = scaler.scaleSlice(polys.getShape());
		Shape zInset = scaler.scaleSlice(polys.calculateInsetPolygons(dist).getShape());
		Shape zBisectors = scaler.scaleSlice(polys.calculateBisectors(dist));

		Area totalArea = new Area();
		totalArea.add(new Area(zOriginal.getBounds2D()));
		totalArea.add(new Area(zInset.getBounds2D()));
		totalArea.add(new Area(zBisectors.getBounds2D()));

		Rectangle2D bounds = totalArea.getBounds();	
		
		System.out.println(bounds);

		int xSize = (int)Math.ceil(Math.max(600, Math.ceil(bounds.getWidth() + 10)));
		int ySize = (int)Math.ceil(Math.max(600, Math.ceil(bounds.getHeight() + 10)));
		//int xSize = 600, ySize = 600;
		BufferedImage imgCanvas = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D) imgCanvas.getGraphics();
		
		g.setBackground(Color.WHITE);
		g.clearRect(0, 0, imgCanvas.getWidth(), imgCanvas.getHeight());

		if (viewOriginal)
		{
			g.setColor(Color.BLACK);
			Color colorTable[] = new Color[]{Color.BLACK, Color.CYAN, Color.RED};
			int i = 0;
			
			ArrayList<ArrayList<Line>> lines = polys.getAllSegments();
			
			for (ArrayList<Line> list : lines)
			{
				for (Line line : list)
				{
					g.draw(scaler.scaleSlice(line));
					
					g.setColor(colorTable[i]);
					
					i = (i+1) % 2;
				}
			}
		}

		if (viewBisectors)
		{
			g.setColor(Color.RED);
			g.draw(zBisectors);
		}

		if (viewInset)
		{
			g.setColor(Color.BLUE);
			g.draw(zInset);
		}

		if (viewVertex)
		{
			PathIterator pi = zOriginal.getPathIterator(null);
			int i = 1;
			
			float coords[] = new float[6];
			while (!pi.isDone())
			{
				pi.currentSegment(coords);

				g.drawString(i + " ", coords[0], coords[1]);
				i++;
				pi.next();
				pi.next();
			}
		}

		if (viewMultColors)
		{

		}
		
		canvas.setImage(imgCanvas);
		display.updatePicture(canvas);
		invalidate();
		repaint();
	}
	
	private void drawAnimated(Shape s, Graphics2D g)
	{
		PathIterator pi = s.getPathIterator(null);        
        
        float cur[] = new float[6], old[] = new float[6];
        
        if (!pi.isDone())
        	pi.currentSegment(old);
        
        while (!pi.isDone())
        {
            int type = pi.currentSegment(cur);
            
            switch (type)
            {
            	case PathIterator.SEG_LINETO:
            	{
            		g.drawLine(Math.round(old[0]), Math.round(old[1]), Math.round(cur[0]), Math.round(cur[1]));
            		break;            		
            	}
            }
            
            System.arraycopy(cur, 0, old, 0, cur.length);
            
            try
			{
				Thread.sleep(250);
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}

	private double zoomAmount = 100;
	private double dist = 0.1;
	private JLabel zoomAmountLbl;
	private JCheckBox jOriginal, jBisectors, jInset, jMultColors, jVertex;
	private boolean viewOriginal = true, viewBisectors = false, viewInset = true, viewVertex = false, viewMultColors = false;

	private SliceScaler scaler;
	private ImageIcon canvas;
	private ScrollablePicture display;
	private PolygonList polys;
}
